/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.moxiu.browser;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.os.SystemClock;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.moxiu.browser.BrowserWebView.OnScrollChangedListener;
import com.moxiu.browser.util.Common;
import com.moxiu.launcher.Insettable;
import com.moxiu.launcher.LauncherApplication;
import com.moxiu.launcher.R;
//import com.tencent.mm.sdk.platformtools.Log;

/**
 * Helper class to manage when to show the URL bar based off of touch
 * input, and when to begin the hide timer.
 */
public class UrlBarAutoShowManager implements OnTouchListener,
        OnScrollChangedListener {

    private static float V_TRIGGER_ANGLE = .9f;
    private static long SCROLL_TIMEOUT_DURATION = 150;
    private static long IGNORE_INTERVAL = 250;

    private static final int MIN_LENGTH_FOR_FLING = 25;
    
    private BrowserWebView mTarget;
    private BaseUi mUi;

    private int mSlop;
    protected int mSnapVelocity = 500;

    private float mStartTouchX;
    private float mStartTouchY;
    private boolean mIsTracking;
    private boolean mHasTriggered;
    private long mLastScrollTime;
    private long mTriggeredTime;
    private boolean mIsScrolling;
    
    private ViewGroup mMainContentContainer;
    private ViewGroup mFixedTitleBarContainer;
    
    private int mFixedTitleBarContainerHeight;
    private ViewGroup mParent;
	private int mMaximumVelocity;
	public boolean flag = true;  //滑动开关（视频全屏用）
	
	public TargetOnShowListener targetOnShowListener;
	
	public void setTargetOnShowListener(TargetOnShowListener targetOnShowListener){
		this.targetOnShowListener=targetOnShowListener;
	}
	
	public interface TargetOnShowListener{
		public void onShow();
	}

    public UrlBarAutoShowManager(BaseUi ui) {
        mUi = ui;
        ViewConfiguration config = ViewConfiguration.get(mUi.getActivity());
        mSlop = config.getScaledTouchSlop() * 2;
        mMaximumVelocity = config.getScaledMaximumFlingVelocity();
        
        mMainContentContainer = mUi.getMainContentView();
        mFixedTitleBarContainer = mUi.getFixTitleBarContainer();
        mFixedTitleBarContainerHeight =  (int) mUi.getActivity().getResources().getDimension(R.dimen.br_title_bar_height);//(int) Common.DipToPixels(mUi.getActivity(), 48);// mMainContentContainer.getHeight();
        mParent = (ViewGroup) mMainContentContainer.getParent();
    }

    public void setTarget(BrowserWebView v) {
        if (mTarget == v) return;

        if (mTarget != null) {
            mTarget.setOnTouchListener(null);
            mTarget.setOnScrollChangedListener(null);
        }
        mTarget = v;
        if (mTarget != null) {
            mTarget.setOnTouchListener(this);
            mTarget.setOnScrollChangedListener(this);
        }
    }
    
    int contentHeight=0;
    int scale=0;

    @Override
    public void onScrollChanged(int l, int t, int oldl, int oldt) {
        mLastScrollTime = SystemClock.uptimeMillis();
        mIsScrolling = true;
        
        if(targetOnShowListener!=null&&mTarget!=null){
        	if(Math.abs((mTarget.getContentHeight()*mTarget.getScale())-mTarget.getHeight()-t)<600){
        		targetOnShowListener.onShow();
        	}
        }
//        if (t != 0) {
//            // If it is showing, extend it
//            if (mUi.isTitleBarShowing()) {
//                long remaining = mLastScrollTime - mTriggeredTime;
//                remaining = Math.max(BaseUi.HIDE_TITLEBAR_DELAY - remaining,
//                        SCROLL_TIMEOUT_DURATION);
//                mUi.showTitleBarForDuration(remaining);
//            }
//        } else {
//            mUi.suggestHideTitleBar();
//        }
    }

    void stopTracking() {
        if (mIsTracking) {
            mIsTracking = false;
            mIsScrolling = false;
            if (mUi.isTitleBarShowing()) {
                mUi.showTitleBarForDuration();
            }
        }
    }

    private float mLastTouchY;
    
    private float mTitleBarTransY = 0;
    private float mMainTransY = 0;
	private int mActivePointerId;
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getPointerCount() > 1) {
            stopTracking();
        }
        
        if (!flag) {
			return false;
		}
        
        acquireVelocityTrackerAndAddMovement(event);
        
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        	mUi.stopEditingUrl();
            if (!mIsTracking && event.getPointerCount() == 1) {
                long sinceLastScroll =
                        SystemClock.uptimeMillis() - mLastScrollTime;
                if (sinceLastScroll < IGNORE_INTERVAL) {
                    break;
                }
                mStartTouchY = event.getRawY();// event.getY();
                mStartTouchX = event.getRawX();//event.getX();
                mIsTracking = true;
                mHasTriggered = false;
                mTitleBarTransY = mFixedTitleBarContainer.getTranslationY();
                mMainTransY = mMainContentContainer.getTranslationY();
                
                mLastTouchY = mStartTouchY;
                mActivePointerId = event.getPointerId(0);
            }
            break;
        case MotionEvent.ACTION_MOVE:
            if (mIsTracking /*&& !mHasTriggered*/) {
                WebView web = (WebView) v;
                
                float lastDy = event.getRawY() - mLastTouchY;
                mLastTouchY = event.getRawY();
                
                float dy = event.getRawY() - mStartTouchY;
                float ady = Math.abs(dy);
                float adx = Math.abs(event.getRawX() - mStartTouchX);
               
                if (ady > mSlop) {
                    mHasTriggered = true;
                    float angle = (float) Math.atan2(ady, adx);
                    if (dy > mSlop && angle > V_TRIGGER_ANGLE
                            && !mUi.isTitleBarShowing()
                            && (web.getVisibleTitleHeight() == 0
                            || (!mIsScrolling && web.getScrollY() > 0))) {
                        mTriggeredTime = SystemClock.uptimeMillis();
                        mUi.showTitleBar();
                    }
                }
                float transY = mTitleBarTransY + dy;
                if (Math.abs(lastDy) > 1) {
                	 float sigsum = Math.signum(transY);
                	 if (Math.abs(transY) > mFixedTitleBarContainerHeight) {
                		 transY = mFixedTitleBarContainerHeight * sigsum;
                	 }
                	 
                	 if (transY > 0) {
                		 transY = 0;
                	 }
                	 mFixedTitleBarContainer.setTranslationY(transY);
                     mMainContentContainer.setTranslationY(transY);
                }
               
            }
            break;
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
        	 
        	 final VelocityTracker velocityTracker = mVelocityTracker;
             velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
             int velocityY = 0;
                 velocityY = (int) velocityTracker.getYVelocity(mActivePointerId);
                 
             boolean isFling = Math.abs(event.getRawY() - mStartTouchY) > MIN_LENGTH_FOR_FLING &&
                     Math.abs(velocityY) > mSnapVelocity;
        	if (isFling) {
        		moveToDest(velocityY < 0);
        	}
            stopTracking();
            releaseVelocityTracker();
            break;
        }
        return false;
    }
    
    void moveToDest(final boolean moveForHide) {
    	
    	
    	
    	final float hasTransY = mFixedTitleBarContainer.getTranslationY();
    	
    	if (moveForHide) {
    		if (hasTransY == -mFixedTitleBarContainerHeight) {
    			return;
    		}
    	} else {
    		if (hasTransY == 0) {
    			return;
    		}
    	}
    	ValueAnimator anim = ValueAnimator.ofFloat(hasTransY, moveForHide ? -mFixedTitleBarContainerHeight : 0);
    	anim.setDuration(200);
    	anim.addUpdateListener(new AnimatorUpdateListener() {
			
			@Override
			public void onAnimationUpdate(ValueAnimator animation) {
				float value = (Float) animation.getAnimatedValue();
				mFixedTitleBarContainer.setTranslationY(value);
				mMainContentContainer.setTranslationY(value);
				
			}
		});
    	anim.addListener(new AnimatorListenerAdapter() {
    		@Override
    		public void onAnimationStart(Animator animation) {
    			// TODO Auto-generated method stub
    			super.onAnimationStart(animation);
    		}
    		
    		@Override
    		public void onAnimationEnd(Animator animation) {
    			if (moveForHide) {
    				mFixedTitleBarContainer.setTranslationY(-mFixedTitleBarContainerHeight);
    				mMainContentContainer.setTranslationY(-mFixedTitleBarContainerHeight);
    			} else {
    				mFixedTitleBarContainer.setTranslationY(0);
    				mMainContentContainer.setTranslationY(0);
    			}
    		}
		});
    	anim.start();
    }
    
    private VelocityTracker mVelocityTracker;
    
    private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(ev);
    }

    private void releaseVelocityTracker() {
        if (mVelocityTracker != null) {
            mVelocityTracker.recycle();
            mVelocityTracker = null;
        }
    }

}
